package taller2.controller.modes.supervisor;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import taller2.interfaces.Connection;
import taller2.interfaces.Graph;
import taller2.interfaces.Node;
import taller2.utils.Constants;
import taller2.utils.Constants.Colores;
import taller2.view.menus.supervisor.ConnectedComponentsSupervisorMenu;

public class ConnectedComponentsSupervisorButtonListener implements ActionListener {
	private ConnectedComponentsSupervisorMenu menu;
	private Graph graph;
	private ArrayList<Node> solution;
	private Node start;
	
	public ConnectedComponentsSupervisorButtonListener(Graph graph,ArrayList<ArrayList<Node>> components, ConnectedComponentsSupervisorMenu menu) {
		this.menu = menu;
		this.graph = graph;		
		this.start = getStartingNode();
		this.solution = getSolution(components);	
		

	}

	private Node getStartingNode(){
		ArrayList<Node> nodes = graph.getNodes();
		for (Node node : nodes){
			Colores color = node.getColor();
			if (color.compareTo(Colores.green) == 0)
				return node;
		}
		return nodes.get(0);
	}
	
	private ArrayList<Node> getSolution(ArrayList<ArrayList<Node>> components) {
		if(components != null){
			for(ArrayList<Node> comp : components){
				for(Node node : comp){
					if(equals(start,node))
						return comp;
				}
			}
		}
		return null;
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		menu.unselectButtons();
		
		if(solution != null){
			HashMap<String, Connection> connections = graph.getAllConnections();
			for(Connection conn : connections.values()){
				Node node1 = conn.getThisNode();
				Node node2 = conn.getOtherNode();
				
				boolean inComponent = isIn(solution,node1) && isIn(solution,node2);
				boolean selected = conn.isSelected();
			
				if((inComponent && !selected) || (!inComponent && selected)){
					JFrame frame = new JFrame();
					JOptionPane.showMessageDialog(frame,Constants.errorMsg);	
					return;
				}
			}
		
			JFrame frame = new JFrame();
			JOptionPane.showMessageDialog(frame,Constants.okMsg);	
		}
	}

	
	// por alguna razon q no puedo explicar, aca no andan los métodos de comparacion
	// normales de nodos, asi q tengo que hacerlo a mano...
	
	private boolean equals(Node n, Node n2) {
		return (n.getNumberId() == n2.getNumberId());
	}
	
	private boolean isIn(ArrayList<Node> s, Node n) {
		for(Node node : s){
			if(equals(node,n))
				return true;
		}
		return false;
	}

}